﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using CometServiceDemo.Comet;
using CometServiceDemo.LocalComunication;

namespace CometServiceDemo
{
    [Activity(Label = "CometServiceDemo", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        int count = 1;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate
                {
                    var intentFilter = new IntentFilter();
                    intentFilter.AddAction(MessageType.Chat);
                    var receive = new CommonBroadcastReceive();
                    receive.OnReceiveBroadcast += new OnReceiveBroadcastDelegate(receive_OnReceiveBroadcast);
                    RegisterReceiver(receive, intentFilter);
                };

            Button buttonStartService = FindViewById<Button>(Resource.Id.button1);
            buttonStartService.Click += new EventHandler(buttonStartService_Click);
            textView = FindViewById<TextView>(Resource.Id.textView1);
            Button buttonStopStreaming = FindViewById<Button>(Resource.Id.button2);
            buttonStopStreaming.Click += new EventHandler(buttonStopStreaming_Click);
        }

        void buttonStopStreaming_Click(object sender, EventArgs e)
        {
            var binder = GlobalApplication.CometServiceConnection.Binder as CommonServiceBinder<CometService>;
            if (binder != null)
            {
                binder.GetCometService().StopStreaming();
            }
        }

        private TextView textView;
        void buttonStartService_Click(object sender, EventArgs e)
        {
            var binder = GlobalApplication.CometServiceConnection.Binder as CommonServiceBinder<CometService>;
            if (binder != null)
            {
                binder.GetCometService().StartStreaming();
            }
        }

        void receive_OnReceiveBroadcast(BroadcastReceiveEventArgs args)
        {
            RunOnUiThread(() => textView.Text = args.ReceiveData);
            //Toast.MakeText(this, args.ReceiveDate, ToastLength.Long).Show();
        }
    }
}

